<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Params\Backend\TagListParams;
use App\Params\Backend\TagUpdateParam;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

/**
 * 标签模型
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Models
 */
class Tag extends BaseModel
{
    protected $table = 'b2c_tags';
    protected $primaryKey = 'tag_id';

    /**
     * 获取标签列表
     *
     * @param TagListParams $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(TagListParams $filter)
    {
        $tags = Tag::query()->where('tag_type', $filter->getType());
        if($filter->getTagName()) {
            $tags->where('tag_name', 'like', '%' . $filter->getTagName() . '%');
        }
        if(Arr::exists([0, 1], $filter->getIsActive())) {
            $tags->where('is_active', $filter->getIsActive());
        }
        $tags->orderByDesc('created_at');
        return $tags;
    }

    /**
     * 根据ID获取标签
     *
     * @param int $tagId
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $tagId)
    {
        return Tag::query()->where('tag_id', $tagId)->first();
    }

    /**
     * 保存标签数据
     *
     * @param TagUpdateParam $data
     * @return mixed
     */
    public static function saveData(TagUpdateParam $data)
    {
        $tag = $data->getTagId() ? Tag::find($data->getTagId()) :new Tag();
        unset($data->tag_id);
        foreach ($data as $field => $val)
        {
            $tag->{$field} = $val;
        }
        return $tag->save() ? $tag->tag_id : 0;
    }

    /**
     * 停用启用标签
     *
     * @param int $tagId
     * @param int $isActive
     * @return int
     */
    public static function enable(int $tagId, int $isActive = 1)
    {
        return Tag::query()->where('tag_id', $tagId)->update(['is_active' => $isActive]);
    }

    /**
     * 检查名称唯一
     *
     * @param string $name
     * @param string $type
     * @param int $id
     * @return bool
     */
    public static function checkName(string $name, string $type, int $id = 0)
    {
        $query = Tag::query()->where('tag_name', $name)->where('tag_type', $type);
        if($id) {
            $query->where('tag_id', '!=', $id);
        }
        return $query->exists();
    }
}
